﻿using YawetagDemo.Framework.Client.Services;
using YawetagDemo.Framework.Impl.Data;
using YawetagDemo.Framework.Impl.Services;
using YawetagLib.System.Data;
using YawetagLib.System.Data.L2Sql;
using YawetagLib.System.Facade.Services;
using YawetagLib.System.Web.Services;

namespace YawetagDemo.WebUI.Startup
{
    internal static class FacadeConfig
    {
        public static void RegisterLocator()
        {
            FacadeFactoryBuilder.RegisterFactoryLocator(typeof(WebFacadeFactoryLocator));
        }

        public static void Initialize()
        {
            if (ConfigurationSet.IS_IN_PROCESS_WORK)
            {
                InitializeInProcessWork();
            }
            else
            {
                InitializeInterProcessWork();
            }
        }

        private static void InitializeInProcessWork()
        {
            DataContextBuilder.RegisterDataContexts(DataContextInfo.New(
                typeof(DbModelDataContext), i => new DataContextAdapter(new DbModelDataContext(ConfigurationSet.CONNECTION_STRING))));

            IFacadeFactory facadeFactory = FacadeFactoryBuilder.GetFactory();

            facadeFactory.RegisterService<CoreService>();
            facadeFactory.RegisterService<MusicService>();
        }

        private static void InitializeInterProcessWork()
        {
            IFacadeFactory facadeFactory = FacadeFactoryBuilder.GetFactory();

            facadeFactory.RegisterService<WCFCoreServiceProxy>();
            facadeFactory.RegisterService<WCFMusicServiceProxy>();
        }

        public static void Release()
        {
            FacadeFactoryBuilder.GetFactory().Dispose();

            if (ConfigurationSet.IS_IN_PROCESS_WORK)
            {
                DataContextBuilder.UnRegisterFactory();
            }
        }
    }
}